package com.happok.onlineclass.usermanagement.setting.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.happok.onlineclass.usermanagement.common.utils.Sm4Util;
import com.happok.onlineclass.usermanagement.setting.dao.SmsDAO;
import com.happok.onlineclass.usermanagement.setting.dto.SmsEnableDTO;
import com.happok.onlineclass.usermanagement.setting.dto.SmsSettingDTO;
import com.happok.onlineclass.usermanagement.setting.po.SmsPO;
import com.happok.onlineclass.usermanagement.setting.service.SmsDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 接口分类                        yapi 分类文件夹
 * 功能说明
 *
 * @author : chenac
 * @module 项目名称/模块名          yapi 项目组/子项目
 * @date : 2021/10/12 9:47
 */
@Service
public class SmsDaoServiceImpl implements SmsDaoService {

    @Autowired
    private SmsDAO smsDAO;

    @Override
    public void updateSmsSetting(SmsSettingDTO smsSetting) {
        LambdaUpdateWrapper<SmsPO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SmsPO::getSmsPlatform, smsSetting.getSmsPlatform());
        SmsPO smsPO = new SmsPO();
        BeanUtil.copyProperties(smsSetting, smsPO);
        smsPO.setSmsPlatform(null);
        if (!ObjectUtils.isEmpty(smsPO.getAccessKeySecret())){
            smsPO.setAccessKeySecret(Sm4Util.encrypt(smsPO.getAccessKeySecret()));
        }
        smsDAO.update(smsPO, updateWrapper);
    }

    @Override
    public List<SmsPO> listSmsSetting() {
        LambdaQueryWrapper<SmsPO> queryWrapper = new LambdaQueryWrapper<>();
        List<SmsPO> smsPOS = smsDAO.selectList(queryWrapper);
        smsPOS = smsPOS.stream().filter(smsPO -> {
            if (!ObjectUtils.isEmpty(smsPO.getAccessKeySecret())){
                smsPO.setAccessKeySecret(Sm4Util.decrypt(smsPO.getAccessKeySecret()));
            }
            return true;
        }).collect(Collectors.toList());
        return smsPOS;
    }

    @Override
    public void smsEnable(SmsEnableDTO smsEnable) {
        if (smsEnable.getEnable()){
            smsDAO.smsDisable(false);
        }
        smsDAO.smsEnable(smsEnable.getSmsPlatform(), smsEnable.getEnable());
    }

    @Override
    public SmsPO getEnableSmsSetting() {
        LambdaQueryWrapper<SmsPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SmsPO::getEnable, true);
        return smsDAO.selectOne(queryWrapper);
    }
}